﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DataBase;

namespace DataBase
{
    /// <summary>
    /// 数据库默认配置
    /// </summary>
    public class CsvWriter
    {

        /// <summary>
        /// 构造函数,当指定路径文件不存则自动创建
        /// </summary>
        /// <param name="path"></param>
        public CsvWriter(string path)
        {
            this.Path = path;
        }

        /// <summary>
        /// 文件路径
        /// </summary>
        public string Path
        {
            private set;
            get;
        }

        /// <summary>
        /// 判断文件路径是否存在
        /// </summary>
        /// <returns>返回布尔值</returns>
        public bool FileExists()
        {
            return (File.Exists(Path));
        }

        /// <summary>
        /// 向文件指定位置追加文本行
        /// </summary>
        /// <param name="batch">批次数据</param>
        /// <param name="isHeader">是否输出表头</param>
        public void WriteLine(bool isHeader, IEnumerable<Batch> batch)
        {
           
            IEnumerable<string> result = RowToString(BatchToRow(batch));
            File.AppendAllLines(Path, result.Select(v => v.ToString()));

        }


        /// <summary>
        /// 将行数据转成字符串格式
        /// </summary>
        /// <param name="row">行数据</param>
        private IEnumerable<string> RowToString(IEnumerable<OracleRow> row)
        {
            foreach (var item in row)
            {
                yield return string.Join(",", item.RowData.Select(v => v.ToString()));
            }
        }

        /// <summary>
        /// 将批次中每行数据放置数据仓库
        /// </summary>
        /// <param name="batch">批次数据</param>
        public IEnumerable<OracleRow> BatchToRow(IEnumerable<Batch> batch)
        {
            OracleRow rw = new OracleRow();
            foreach (Batch rowList in batch)
            {
                foreach (var item in rowList.RowsList)
                {
                    rw.RowData = item;
                    yield return rw;
                }
            }
        }

    }
}
